<!-- 切换账号 -->
<template>
	<view>
	<view class="main">
		<div v-for="(item, index) in items" :key="index"  >
		<view class="content-item">
			<p class="content-item-list" @click="login(item,index)">
				<span><image src="../../../static/人物.png" style="width: 15px; height: 15px;position: relative;top: 2px;border-radius: 5px;"></image></span>
				<span class="item-name">企业ID:</span>
				<span class="item-name">{{item.enterpriseId}}</span>
				<span class="item-phone">{{item.phone}}</span>
				<span class="item-ed" @click.stop="headEid(item,index)">编辑</span>
				<span class="item-text">|</span>
				<span class="item-del" @click.stop="headDel(item,index)">删除</span>
			</p>
		</view>
		</div>
		<view class="end" >
			<button class="end-button" @click="showInputModal">新增账号</button>
		</view>
	</view>
	<BillModal ref="inputModal" @add-item="addItem" />
	<tips ref="tipsModal" @confirm="confirm" :userId="userId" :subaccountId="id" :name="name" :phone="phone" :type="type"/>
	</view>
</template>

<script>
	import {getSon,detelSon} from '@/api/bill.js';
	import {goPhoneCode} from '@/api/login.js';
	import BillModal from '@/pages/components/accountModel/accountModel.vue';	
	import tips from '@/pages/components/tips/tips.vue';	
	import { removeToken } from '@/util/auth.js'; 
	import { setToken } from '@/util/auth.js'; 
	import { setEenterpriseId } from '@/util/auth.js'; 
	export default {
		components: {
			BillModal,
			tips
		 },
		data() {
			return {
				items:[
				],
				userId:0,
				id:0,
				type:'',
				account:{},
				req:{},
				subaccount:'',
				phone:'',
				userName:'',
			}
		},
		mounted(){
			this.getList();
		},
		methods: {
			login(item,index){
				let enterpriseId=item.enterpriseId;
				let password=item.password;
				let phone=item.phone;
				this.req.enterpriseId=enterpriseId;
				this.req.password=password;
				this.req.phone=phone;
				setEenterpriseId(enterpriseId)
				goPhoneCode(this.req).then(res =>{
					// 请求成功
					if (res.statusCode === 200) {
						this.userName=res.data.data.userName
						this.phone=res.data.data.phone
						this.userId=res.data.data.userId
						if(res.data.data.subaccount==null){
							this.subaccount=false;
						}else{
							this.subaccount=true;
						}
						console.log(this.subaccount)
						removeToken();
						const token=res.data.data.token;
						setToken(token);
						uni.redirectTo({
						    url: '/pages/index/index?userName='+this.userName+'&phone='+this.phone+'&userId='+this.userId+'&subaccount='+this.subaccount ,// 请注意，这里的url应为相对路径，且以'/'开头
						});
						uni.showToast({
						    title: '登录成功',
						    icon: 'success',
						});
					}
				})
			},
			addItem(data){
				let enterpriseId=data.name;
				let password=data.password;
				let phone=data.phone;
				this.req.enterpriseId=enterpriseId;
				this.req.password=password;
				this.req.phone=phone;
				setEenterpriseId(enterpriseId)
				goPhoneCode(this.req).then(res =>{
					console.log(res)
					// 请求成功
					if(res.data.code===400){
						uni.showToast({
						    title: res.data.errorMessage,
						    icon: 'none',
						});
					}else if (res.data.code === 20000) {
				    let accounts={phone: phone, password: password, enterpriseId: enterpriseId}
				    const storedAccounts = uni.getStorageSync('accounts') || [];
					if(this.type==='新增'){
						 // 检查新账户的 ID 是否已在数组中
						  const hasDuplicateId = storedAccounts.some(account => account.phone === accounts.phone && account.enterpriseId === accounts.enterpriseId);
						  if (hasDuplicateId) {
						      // 如果 ID 已存在，则不更新并发出警告
						      console.warn('存在重复的账户 ID，无法更新账户');
							  uni.showToast({
							      title: '存在重复的账户 ID，无法新增账户',
							      icon: 'none',
							  });
						    } else {
						     storedAccounts.push(accounts)
						     uni.setStorageSync('accounts',storedAccounts);
							 this.getList();
						    }
					}
					if(this.type==='修改'){
						const indexToUpdate = this.id; // 替换为实际的索引值
						// 假设我们要将索引为indexToUpdate的账户更新为newAccount对象
						const newAccount = {
						 phone: phone, password: password, enterpriseId: enterpriseId
						};
						 console.log(indexToUpdate);
						// 检查索引是否在数组范围内
						if (indexToUpdate >= 0 && indexToUpdate < storedAccounts.length) {
							// 检查新账户的 ID 是否已在数组中
							 const hasDuplicateId = storedAccounts.some(account => account.phone === accounts.phone && account.enterpriseId === accounts.enterpriseId);
							 if (hasDuplicateId) {
							     // 如果 ID 已存在，则不更新并发出警告
							     console.warn('存在重复的账户 ID，无法更新账户');
								 uni.showToast({
								     title: '存在重复的账户 ID，无法新增账户',
								     icon: 'none',
								 });
							   } else {
						       // 直接修改数组中指定索引的元素
						       storedAccounts[indexToUpdate] = newAccount;
						       // 将更新后的数组存回本地缓存
						       uni.setStorageSync('accounts', storedAccounts);
							   this.getList();
						       // 如果需要，可以输出更新后的数组以进行验证
						      }
						} else {
						  console.warn('索引超出数组范围，无法更新账户');
						}
					}
					
				}else{
					uni.showToast({
					    title: '账号或密码错误',
					    icon: 'none',
					});
				}
				})
				
			},
			getList(){
				const storedAccounts = uni.getStorageSync('accounts') || [];
				const loginPhone = uni.getStorageSync('username_key') || [];
				console.log(loginPhone);
				// 初始化 items 为空数组，稍后将根据需要填充
				this.items = [];
				 
				// 遍历 storedAccounts 数组
				for (let i = 0; i < storedAccounts.length; i++) {
				  const account = storedAccounts[i];
				  const phone = account.phone; // 从当前账户对象中获取 phone 属性
				 
				  // 检查 phone 是否与 loginPhone 相等
				  if (phone === loginPhone) {
				    // 如果相等，将当前账户对象添加到 items 数组中
				    this.items.push(account);
				  }
				}
				
			},
			confirm(data){
				if(data===true){
					
					const storedAccounts = uni.getStorageSync('accounts') || [];
					// 假设我们要删除的账户的索引是indexToDelete
					const indexToDelete = this.id; // 替换为实际的索引值
					 console.log(indexToDelete)
					// 检查索引是否在数组范围内
					if (indexToDelete >= 0 && indexToDelete < storedAccounts.length) {
					  // 使用splice方法从数组中删除指定索引的元素
					  storedAccounts.splice(indexToDelete, 1);
					 
					  // 将更新后的数组存回本地缓存
					  uni.setStorageSync('accounts', storedAccounts);
					 
					  // 如果需要，可以输出更新后的数组以进行验证
					  this.getList();
					} else {
					  console.warn('索引超出数组范围');
					}
				}
				
			},
			headEid(item,index){
				let req={}
				console.log(item)
				req.phone=item.phone;
				req.enterpriseId=item.enterpriseId;
				req.password=item.password;
				req.id=index;
				req.type='修改';
				this.type='修改';
				this.id=index;
				  this.$refs.inputModal.showModal('修改账号', {
				    onConfirm: (value) => {
				      console.log('用户输入:', value);
				      // 在这里处理用户输入的内容
				    },
				    onCancel: () => {
				      console.log('用户取消了输入');
				    }
				  },req);
			},
			headDel(item,index){
				this.id=index;
				const title='是否删除 [ '+item.phone+' ] 账号'
				this.$refs.tipsModal.showModal(title, {
				  onConfirm: (value) => {
				    console.log('用户输入:', value);
				    // 在这里处理用户输入的内容
				  },
				  onCancel: () => {
				    console.log('用户取消了输入');
				  }
				});
			},
			showInputModal(item, index) {
				this.id=item.id;
				this.type='新增';
			      this.$refs.inputModal.showModal('新增账号', {
			        onConfirm: (value) => {
			          console.log('用户输入:', value);
			          // 在这里处理用户输入的内容
			        },
			        onCancel: () => {
			          console.log('用户取消了输入');
			        }
			      });
			    },
		}
	}
</script>

<style>
@import "management.css";
</style>
